package com.gongpingjialoan.activity.car;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseFragment;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.activity.main.RankActivity;
import com.gongpingjialoan.adapter.CarSourceListAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.api.Piont;
import com.gongpingjialoan.bean.CarSource;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.bean.car.FindCarBean;
import com.gongpingjialoan.bean.car.ModelDetialBean;
import com.gongpingjialoan.data.CarListFilterData;
import com.gongpingjialoan.data.CategoryData;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.DhUtil;
import com.gongpingjialoan.utility.SharedPreferencesUtil;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.UserLocation;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.view.NewSortLinearLayout;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import scrollable.CanScrollVerticallyDelegate;
import scrollable.OnFlingOverListener;
import scrollable.OnScrollChangedListener;
import scrollable.ScrollableLayout;

import static android.content.Context.MODE_PRIVATE;

/***
 * 更多车源(买车-专家模式) hqh
 *
 * @author Administrator
 */
public class CarListFragment extends BaseFragment implements OnClickListener, AbsListView.OnItemClickListener, NetDataJson.OnNetDataJsonListener,
        OnRefreshListener<ListView>, OnLastItemVisibleListener, NewSortLinearLayout.GeCarList {

    public CategoryData mCategoryData;

    public CarListFilterData data;

    public static final String FROM_FILTER = "formFilter";
    public static final String FROM_Hot = "formHot";
    public static final String FROM_Esimate = "formEsimate";
    private static final int REQUEST_BRAND_SORT = 0x298;

    private View mainV, distanceView;

    private PullToRefreshListView pullToRefreshListView;

    private ListView listView;

    private CarSourceListAdapter carSourceAdapter;

    private int pageIndex;

    private boolean isLoadingMore;

    private boolean hasMore, isSuggest;

    private List<CarSource> carSourceDataList;

    private NetDataJson netWork;

    private boolean isRefresh = true;

    private NewSortLinearLayout mSortLinearLayout;

    // request network need item:
    private String brand = "", model = "", price = "", sort = "", brand_name = "", model_name = "", max_Price = "";

    private String age = "", color = "", mile = "", vehicle_model = "", car_type = "", car_attribute = "", car_volume = "", control = "", domain = "";

    private String cityName = "", provice = "";


    private ImageView nocarImageView;

    public String fromType = "";

    private View footView;

    public int front_cover = 1;

    private View loading;

    private View suggestHeadView, tabview, headerView;

    private RelativeLayout mainRelativeLayout;

    private ImageView vip_wayImageView;

    private RadioButton allCarsRadioButton, privateRadioButton, dealersRadioButton;

    private int width, height;

    private LinearLayout mainLinearLayout;

    private String isCut = "0";

    private String is_certify = "0";

    private NetDataJson modelDetailnetWork;
    private ScrollableLayout mScrollableLayout;

    //用途    (多选)
    public static String[] show_carModel = {"微型车", "小型车", "紧凑型车", "中级车", "中高级车", "SUV", "跑车", "豪华车", "商务车", "车型不限"};
    public static String[] need_carModel = {"mini_car", "small_car", "compact_car", "middle_car", "middle_super_car", "suv", "super_car", "luxury_car", "mpv", ""};

    //车辆属性  (多选)
    private String[] show_carProperty = {"进口", "合资", "国产", "产地不限"};
    private String[] need_carProperty = {"import", "joint_venture", "domestic", ""};

    //变速箱 (多选)
    private String[] show_speedChange = {"手动", "自动", "不限"};
    private String[] need_speedChange = {"manual", "automatic", ""};


    private int top1, top2;
    private ImageView rank_im;
    private ImageView vip_way_new;
    private LinearLayout banner_ll;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        isScrollPage = true;
        action = "buy_market";
        super.onCreate(savedInstanceState);
    }

    @SuppressLint("InflateParams")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mCategoryData = GPJApplication.getInstance().getCategoryData();
        width = DhUtil.dip2px(getActivity(), 6);
        height = DhUtil.dip2px(getActivity(), 4);
        top1 = DhUtil.dip2px(getActivity(), 70);
        top2 = DhUtil.dip2px(getActivity(), 105);
        mainV = inflater.inflate(R.layout.carlist_fragment, null);
        footView = inflater.inflate(R.layout.listview_footview, null);
        suggestHeadView = inflater.inflate(R.layout.suggest_head, null);
        suggestHeadView.setOnClickListener(this);
        netWork = new NetDataJson(this);
        initView();
        if (!(boolean) SharedPreferencesUtil.get(getActivity(), "isShowVipPage", false) && MainActivity.main.isShowVip) {

            UserManager mUserManager = new UserManager(getActivity());
            mUserManager = mUserManager.LoadUserInfo();
            //如果没有设置vip筛选条件,先跳转到设置页面
            if (!mUserManager.isBuy_car_recommend_flag()) {
                startActivity(new Intent(getActivity(), BuyCarVipActivity.class));
                SharedPreferencesUtil.put(getActivity(), "isShowVipPage", true);
            }


        } else {
            MainActivity.main.isShowVip = true;
        }
        return mainV;
    }


    private void initView() {
        mainRelativeLayout = (RelativeLayout) mainV.findViewById(R.id.main_relate);
        mScrollableLayout = (ScrollableLayout) mainV.findViewById(R.id.scrollable_layout);
        tabview = mainV.findViewById(R.id.tabs);
        headerView = mainV.findViewById(R.id.header);
        mScrollableLayout.setDraggableView(tabview);
        mScrollableLayout.setOnScrollChangedListener(new OnScrollChangedListener() {
            @Override
            public void onScrollChanged(int y, int oldY, int maxY) {
                Utils.LogD("y=" + y + "oldY=" + oldY + "y=" + maxY);
                final float tabsTranslationY;
                if (y < maxY) {
                    tabsTranslationY = .0F;
                } else {
                    tabsTranslationY = y - maxY;
                }
                tabview.setTranslationY(tabsTranslationY);
                headerView.setTranslationY(y / 2);
            }
        });


        distanceView = mainV.findViewById(R.id.distance);
        allCarsRadioButton = (RadioButton) mainV.findViewById(R.id.radio1);
        privateRadioButton = (RadioButton) mainV.findViewById(R.id.radio2);
        dealersRadioButton = (RadioButton) mainV.findViewById(R.id.radio3);
        mainLinearLayout = (LinearLayout) mainV.findViewById(R.id.mainlinear);
        mSortLinearLayout = (NewSortLinearLayout) mainV.findViewById(R.id.menu_layout);
        mSortLinearLayout.setGeCarList(this);

        //  Utils.initNotification(getActivity(), "buycar", linearNotLinearLayout, notTextView, notImageView, "Cb1_banner");
        MainActivity activity = (MainActivity) getActivity();
        activity.getFilterTextView().setVisibility(View.VISIBLE);
        nocarImageView = (ImageView) mainV.findViewById(R.id.no_car_id);
        loading = mainV.findViewById(R.id.main_loading);
        vip_wayImageView = (ImageView) mainV.findViewById(R.id.vip_way);
        vip_way_new = (ImageView) mainV.findViewById(R.id.vip_way_new);
        banner_ll = (LinearLayout) mainV.findViewById(R.id.banner_ll);
        rank_im = (ImageView) mainV.findViewById(R.id.rank_im);
        rank_im.setOnClickListener(this);
        vip_way_new.setOnClickListener(this);
        vip_wayImageView.setOnClickListener(this);


        pullToRefreshListView = (PullToRefreshListView) mainV.findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnLastItemVisibleListener(this);
        carSourceDataList = new ArrayList<CarSource>();

        pageIndex = 1;
        isLoadingMore = true;
        hasMore = true;

        carSourceAdapter = new CarSourceListAdapter(getActivity(), 1);
        listView = pullToRefreshListView.getRefreshableView();
        listView.addHeaderView(suggestHeadView);
        listView.addFooterView(footView);
        listView.setAdapter(carSourceAdapter);
        listView.setOnItemClickListener(this);
        listView.removeHeaderView(suggestHeadView);
        listView.removeFooterView(footView);
        carSourceAdapter.notifyDataSetChanged();

        mScrollableLayout.setCanScrollVerticallyDelegate(new CanScrollVerticallyDelegate() {
            @Override
            public boolean canScrollVertically(int direction) {
                return listView != null && listView.canScrollVertically(direction);
            }
        });
        mScrollableLayout.setOnFlingOverListener(new OnFlingOverListener() {
            @Override
            public void onFlingOver(int y, long duration) {
                if (listView != null) {
                    listView.smoothScrollBy(y, (int) duration);
                }
            }
        });
        distanceView.setOnClickListener(this);
        allCarsRadioButton.setOnClickListener(this);
        privateRadioButton.setOnClickListener(this);
        dealersRadioButton.setOnClickListener(this);

        getSaveData("");
        onUpdateData();

        String campaign_id = getActivity().getSharedPreferences("NEW_CAR_ACTIVITY", MODE_PRIVATE).getString("campaign_id", "");
        updateBanner(!TextUtils.isEmpty(campaign_id));
    }


    public String getMaxPriceFromBrand(String brand) {
        List<Map<String, String>> maps = mCategoryData.mBrandList;
        int size = maps.size();
        for (int i = 0; i < size; i++) {
            Map<String, String> map = maps.get(i);
            if (brand.equals(map.get("slug"))) {
                return map.get("max_price_bn");
            }
        }
        return "";
    }

    //获取筛选条件
    public void getSaveData(String type) {
        max_Price = "999";
        getData();
        if (!TextUtils.isEmpty(brand)) {
            if (data.isCleanData()) {
                front_cover = 0;
                car_attribute = "";
                data.setCar_attribute(car_attribute);
                data.setShow_source("");
                allCarsRadioButton.setChecked(true);
            }
            front_cover = 0;
            if (!TextUtils.isEmpty(model)) {
                if (!CarListFragment.FROM_FILTER.equals(type)) {
                    getModelDetailData(brand, model);
                } else {
                    max_Price = data.getMax_price();
                    mSortLinearLayout.setMaxPrice(max_Price);
                }
            } else {
                max_Price = getMaxPriceFromBrand(brand);
                mSortLinearLayout.setMaxPrice(max_Price);
                addFilterView();
            }
            return;
        }
        mSortLinearLayout.setMaxPrice(max_Price);
        if (data.isCleanData()) {
            front_cover = 0;
            car_attribute = "";
            data.setCar_attribute(car_attribute);
            data.setShow_source("");
            allCarsRadioButton.setChecked(true);
            addFilterView();
        }
    }

    public void getData() {
        data = CarListFilterData.getInstance();
        cityName = data.getCity();
        provice = data.getProvince();
        if (TextUtils.isEmpty(cityName) && TextUtils.isEmpty(provice)) {
            if (data.isCounty()) {
                cityName = "";
                provice = "";
            } else {
                cityName = MainActivity.main.currentCity;
            }

        }
        brand = data.getBrandSlug();
        model = data.getModelSlug();
        sort = data.getSort();
        mSortLinearLayout.setBrand(brand);
        mSortLinearLayout.setModel(model);
        mSortLinearLayout.setBrandName(data.getBrandName());
        mSortLinearLayout.setModelName(data.getModelName());
        mSortLinearLayout.setBrandColor();
        price = data.getPrice();
        mSortLinearLayout.setPriceView(price);
        age = data.getYear();
        color = data.getColor();
        vehicle_model = data.getVehicle_model();
        car_type = data.getCar_type();
        car_attribute = data.getCar_attribute();
        car_volume = data.getCar_volume();
        control = data.getControl();
        is_certify = data.getIs_certify();
        isCut = data.getIsCut();
        domain = data.getCar_domain();
        mile = data.getMile();
        mSortLinearLayout.setNoSortColor(sort, is_certify, isCut);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (netWork != null) {
            netWork.cancelTask();
        }
        if (modelDetailnetWork != null) {
            modelDetailnetWork.cancelTask();
        }
    }


    @Override
    public void onClick(View v) {
        if (v == vip_wayImageView || v == vip_way_new) {
            PointRecordManage.getInstance().addPoint(getActivity(), Piont.MarketBannerVIP);
            Intent vipit = new Intent(getActivity(), BuyCarVipActivity.class);
            vipit.putExtra("from", "carlist");
            startActivity(vipit);
        } else if (v == rank_im) {
            startActivity(new Intent(getActivity(), RankActivity.class));
        } else if (v == distanceView) {
            StepMonitor.getInstance().addMonitor(new Monitor("click", "buy_market_nearByCar", System.currentTimeMillis(), 1f));
            sort = "distance";
            front_cover = 0;
            mSortLinearLayout.setPosition(4);
            mSortLinearLayout.setSort(sort);
            if (pullToRefreshListView.isRefreshing()) pullToRefreshListView.onRefreshComplete();
            pullToRefreshListView.setRefreshing();
        } else if (v == allCarsRadioButton && !"".equals(car_attribute)) {
            car_attribute = "";
            data.setCar_attribute(car_attribute);
            data.setShow_source("");
            if (pullToRefreshListView.isRefreshing()) pullToRefreshListView.onRefreshComplete();
            pullToRefreshListView.setRefreshing();
        } else if (v == privateRadioButton && !"private".equals(car_attribute)) {
            car_attribute = "private";
            data.setShow_source("个人");
            data.setCar_attribute(car_attribute);
            front_cover = 0;
            StepMonitor.getInstance().addMonitor(new Monitor("click", "buy_market_personalCar", System.currentTimeMillis(), 1f));
            if (pullToRefreshListView.isRefreshing()) pullToRefreshListView.onRefreshComplete();
            pullToRefreshListView.setRefreshing();
        } else if (v == dealersRadioButton && !"dealer".equals(car_attribute)) {
            car_attribute = "dealer";
            data.setCar_attribute(car_attribute);
            data.setShow_source("商家");
            front_cover = 0;
            StepMonitor.getInstance().addMonitor(new Monitor("click", "buy_market_dealerCar", System.currentTimeMillis(), 1f));
            if (pullToRefreshListView.isRefreshing()) pullToRefreshListView.onRefreshComplete();
            pullToRefreshListView.setRefreshing();
        }
    }

    public void updateListView() {
        if (carSourceDataList.size() != 0) {
            carSourceAdapter.setData(carSourceDataList);
            pullToRefreshListView.onRefreshComplete();
            nocarImageView.setVisibility(View.GONE);
            isLoadingMore = false;
        } else {
            nocarImageView.setVisibility(View.VISIBLE);
        }
    }


    public void refresh() {
        if (pullToRefreshListView != null) {
            pullToRefreshListView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    pullToRefreshListView.setRefreshing();
                }
            }, 300);
        }
    }

    // 重新获取数据
    private void onUpdateData() {
        if (pullToRefreshListView.isRefreshing())
            loading.setVisibility(View.GONE);
        isRefresh = true;
        nocarImageView.setVisibility(View.GONE);
        pageIndex = 1;
        hasMore = true;
        updateData();

    }


    private void updateData() {
        netWork.clearMap();
        netWork.setUrl(API.carListSearch);
        netWork.addParam("city", cityName);
        netWork.addParam("province", provice);
        netWork.addParam("page", pageIndex);
        netWork.addParam("front_cover", front_cover);
        netWork.addParam("is_cut_price", isCut);
        netWork.addParam("is_certify", is_certify);

        if (UserLocation.getInstance().isIslocation()) {
            netWork.addParam("lat", UserLocation.getInstance().getLatitude());
            netWork.addParam("lng", UserLocation.getInstance().getLongitude());
        }
        if (!TextUtils.isEmpty(brand))
            netWork.addParam("brand", brand);
        if (!TextUtils.isEmpty(mile))
            netWork.addParam("mile", mile);
        if (!TextUtils.isEmpty(model))
            netWork.addParam("model", model);
        if (!TextUtils.isEmpty(price))
            netWork.addParam("price", price);
        if (!TextUtils.isEmpty(age))
            netWork.addParam("year", age);
        if (!TextUtils.isEmpty(sort))
            netWork.addParam("sort", sort);
        if (!TextUtils.isEmpty(color))
            netWork.addParam("colors", color);
        if (!TextUtils.isEmpty(vehicle_model))
            netWork.addParam("vehicle_model", vehicle_model);
        if (!TextUtils.isEmpty(car_type))
            netWork.addParam("car_type", car_type);
        if (!TextUtils.isEmpty(car_attribute))
            netWork.addParam("car_attribute", car_attribute);
        if (!TextUtils.isEmpty(car_volume))
            netWork.addParam("car_volume", car_volume);
        if (!TextUtils.isEmpty(control))
            netWork.addParam("control", control);
        if (!TextUtils.isEmpty(domain))
            netWork.addParam("domain", domain);
        netWork.request("get");

    }


    // 加载更多
    private void LoadMoreData() {
        if (!hasMore) {
            Toast.makeText(getActivity(), "没有更多了", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isLoadingMore && hasMore && carSourceDataList.size() > 0) {
            listView.addFooterView(footView);
            listView.setSelection(listView.getBottom());
            isRefresh = false;
            isLoadingMore = true;
            pageIndex++;
            updateData();
        }
    }


    @Override
    public void onDataJsonError(String errorMessage) {
        Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
        loading.setVisibility(View.GONE);
        if (isLoadingMore && !isRefresh) {
            listView.removeFooterView(footView);
        }
        isLoadingMore = false;
        hasMore = false;
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        JSONArray jsonArray = null;
        loading.setVisibility(View.GONE);
        if (isLoadingMore && !isRefresh) {
            listView.removeFooterView(footView);
        }
        if (isRefresh) {
            carSourceDataList.clear();
            listView.removeHeaderView(suggestHeadView);
            carSourceAdapter.notifyDataSetChanged();
        }
        try {
            jsonArray = json.getJSONArray("car_list");
            // Log.e("jsonArray", jsonArray.toString());
            if (0 == jsonArray.length()) {
                JSONArray suggestJsonArray = json.getJSONArray("suggest_list");
                if (suggestJsonArray.length() == 0) {
                    Toast.makeText(getActivity(), "未找到相应数据", Toast.LENGTH_SHORT).show();
                    nocarImageView.setVisibility(View.VISIBLE);
                    isLoadingMore = false;
                    pullToRefreshListView.onRefreshComplete();
                    isSuggest = false;
                } else {
                    //建议车源
                    isSuggest = true;
                    isLoadingMore = false;
                    hasMore = false;
                    pullToRefreshListView.onRefreshComplete();
                    listView.addHeaderView(suggestHeadView);
                    getDataFromJsonArray(suggestJsonArray);
                    updateListView();

                }
                return;
            }

            if (distanceView.getVisibility() == View.GONE && UserLocation.getInstance().isIslocation()) {
                distanceView.setVisibility(View.VISIBLE);
            }
            isSuggest = false;
            getDataFromJsonArray(jsonArray);

            int page_num = json.getInt("page_num");
            if (page_num == pageIndex) {
                hasMore = false;
            }

        } catch (JSONException e) {
            isLoadingMore = false;
            hasMore = false;
            Toast.makeText(getActivity(), "未找到相应数据", Toast.LENGTH_SHORT).show();
            pullToRefreshListView.onRefreshComplete();
            return;
        }

        updateListView();
    }

    private void getDataFromJsonArray(JSONArray jsonArray) throws JSONException {
        // Log.e("getDataFromJsonArray", "getDataFromJsonArray");
        for (int i = 0; i < jsonArray.length(); i++) {
            CarSource carSrc = new CarSource();
            JSONObject object = jsonArray.getJSONObject(i);
            carSrc.mCity = cityName;
            if (isMoreCity() || isSuggest) {
                carSrc.newCity = object.getString("city");
            }
            carSrc.distance = object.getString("distance");
            carSrc.mTitle = object.getString("title");
            carSrc.mYear = object.getString("year");
            carSrc.mMile = object.getString("mile").equals("None") ? "" : object.getString("mile");
            carSrc.mPrice = Double.valueOf(object.getString("price"));
            carSrc.mId = object.getInt("id");
            carSrc.isViewed = object.getBoolean("viewed");
            carSrc.mThumbnail = object.getString("thumbnail");
            carSrc.mTime = object.getString("time");
            carSrc.hasmodel = object.getString("has_model_detail");
            carSrc.is_certify = object.getBoolean("is_certify");
            carSrc.pub_timestamp = object.getString("pub_timestamp");
            // carSrc.mRecommend = object.getString("recommend");
            carSrc.mSourceType = object.getString("source_type");
            carSrc.mGpjIndex = object.getDouble("gpj_index");
            carSrc.mQsTags = object.getString("qs_tags");
            carSrc.mSource = object.getString("domain");
            carSrc.dealer_category = object.getString("dealer_category");
            carSrc.pubTime = object.getString("pub_time");
            carSrc.brand_zh = object.getString("brand_slug_zh");
            carSrc.model_zh = object.getString("model_slug_zh");
            carSrc.model_detail_zh = object.getString("model_detail_slug_zh");
            carSrc.isactive = object.getBoolean("seller_active");
            carSrc.origin_price = object.getString("origin_price");
            carSrc.lowest_price = object.getString("lowest_price");
            carSrc.last_price = object.getString("last_price");

            carSrc.cs_clean = object.getBoolean("cs_clean");
            carSrc.setBrand(object.getString("brand_slug"));
            carSrc.setModel(object.getString("model_slug"));

            carSrc.mUrl = carSrc.mThumbnail;
            carSourceDataList.add(carSrc);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        if (position == 0) return;
        Intent intent = new Intent();
        intent.setClass(getActivity(), CarBuyDetailActivity.class);
        CarSource carSource = (CarSource) arg1.getTag(R.id.tag_second);
        if (carSource == null) return;
        intent.putExtra("typevalue", String.valueOf(carSource.mId));
        intent.putExtra("type", fromType);
        intent.putExtra("from", "buycar");
        intent.putExtra("city", data.getCity());
        intent.putExtra("province", data.getProvince());
        startActivity(intent);
        carSource.isViewed = true;
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                carSourceAdapter.notifyDataSetChanged();
            }
        }, 300);

    }


    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        StepMonitor.getInstance().addMonitor(new Monitor("scroll", action, System.currentTimeMillis(), roll_pages));
        reset();
        String label =
                "更新时间:" + DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                        | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
        refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        onUpdateData();
    }

    @Override
    public void onLastItemVisible() {
        LoadMoreData();
    }

//    @Override
//    public void getCar(String sort) {
//        this.sort = sort;
//        refresh();
//    }


    public void addFilterView() {
        mainLinearLayout.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        String mulchooses[];
        String valuechooses[];
        final List<FindCarBean> datas = new ArrayList<>();
        if (!TextUtils.isEmpty(data.getBrandSlug())) {
            if (TextUtils.isEmpty(data.getModelSlug())) {
                datas.add(new FindCarBean(data.getBrandName(), "", "brand"));
            } else {
                datas.add(new FindCarBean(data.getModelName(), "", "model"));
            }
        }

        if (!TextUtils.isEmpty(data.getPrice())) {
            datas.add(new FindCarBean(data.getShow_price(), "", "price"));
        }

        if ("1".equals(is_certify)) {
            datas.add(new FindCarBean("认证好车", is_certify, "is_certify"));
        }

        if ("1".equals(isCut)) {
            datas.add(new FindCarBean("降价", isCut, "isCut"));
        }

        //颜色
        if (!TextUtils.isEmpty(data.getMile())) {
            mulchooses = data.getShowmile().split(",");
            valuechooses = data.getMile().split(",");
            for (int i = 0; i < mulchooses.length; i++) {
                if (!TextUtils.isEmpty(mulchooses[i])) {
                    datas.add(new FindCarBean(mulchooses[i], valuechooses[i], "mile"));
                }
            }
            // datas.add(new FindCarBean(mFindCarData.getShow_vehicle_model(), "vehicle_model"));
        }

        if (!TextUtils.isEmpty(data.getYear())) {
            mulchooses = data.getShow_age().split(",");
            valuechooses = data.getYear().split(",");
            for (int i = 0; i < mulchooses.length; i++) {
                if (!TextUtils.isEmpty(mulchooses[i])) {
                    datas.add(new FindCarBean(mulchooses[i], valuechooses[i], "age"));
                }
            }
            //   datas.add(new FindCarBean(mFindCarData.getShow_age(), "age"));
        }


        //颜色
        if (!TextUtils.isEmpty(data.getColor())) {
            mulchooses = data.getShow_color().split(",");
            valuechooses = data.getColor().split(",");
            for (int i = 0; i < mulchooses.length; i++) {
                if (!TextUtils.isEmpty(mulchooses[i])) {
                    datas.add(new FindCarBean(mulchooses[i], valuechooses[i], "color"));
                }
            }
            // datas.add(new FindCarBean(mFindCarData.getShow_vehicle_model(), "vehicle_model"));
        }


        //车型
        if (!TextUtils.isEmpty(data.getVehicle_model())) {
            mulchooses = data.getShow_vehicle_model().split(",");
            valuechooses = data.getVehicle_model().split(",");
            for (int i = 0; i < mulchooses.length; i++) {
                if (!TextUtils.isEmpty(mulchooses[i])) {
                    datas.add(new FindCarBean(mulchooses[i], valuechooses[i], "vehicle_model"));
                }
            }
            // datas.add(new FindCarBean(mFindCarData.getShow_vehicle_model(), "vehicle_model"));
        }

//        //车源类型
//        if (!TextUtils.isEmpty(data.getCar_attribute())) {
//            mulchooses = data.getShow_source().split(",");
//            valuechooses = data.getCar_attribute().split(",");
//            for (int i = 0; i < mulchooses.length; i++) {
//                if (!TextUtils.isEmpty(mulchooses[i])) {
//                    datas.add(new FindCarBean(mulchooses[i], valuechooses[i], "attribute"));
//                }
//            }
//            // datas.add(new FindCarBean(mFindCarData.getShow_vehicle_model(), "vehicle_model"));
//        }

        //产地
        if (!TextUtils.isEmpty(data.getCar_type())) {
            mulchooses = data.getShow_car_type().split(",");
            valuechooses = data.getCar_type().split(",");
            for (int i = 0; i < mulchooses.length; i++) {
                if (!TextUtils.isEmpty(mulchooses[i])) {
                    datas.add(new FindCarBean(mulchooses[i], valuechooses[i], "car_type"));
                }
            }
            // datas.add(new FindCarBean(mFindCarData.getShow_car_type(), "car_type"));
        }

        //排量
        if (!TextUtils.isEmpty(data.getCar_volume())) {
            mulchooses = data.getShow_displacement().split(",");
            valuechooses = data.getCar_volume().split(",");
            for (int i = 0; i < mulchooses.length; i++) {
                if (!TextUtils.isEmpty(mulchooses[i])) {
                    datas.add(new FindCarBean(mulchooses[i], valuechooses[i], "volume"));
                }
            }
            // datas.add(new FindCarBean(mFindCarData.getShow_car_type(), "car_type"));
        }

        //变速箱
        if (!TextUtils.isEmpty(data.getControl())) {
            mulchooses = data.getShow_speedchange().split(",");
            valuechooses = data.getControl().split(",");
            for (int i = 0; i < mulchooses.length; i++) {
                if (!TextUtils.isEmpty(mulchooses[i])) {
                    datas.add(new FindCarBean(mulchooses[i], valuechooses[i], "speedchange"));
                }
            }
            // datas.add(new FindCarBean(mFindCarData.getShow_car_type(), "car_type"));
        }


        //变速箱
        if (!TextUtils.isEmpty(data.getCar_domain())) {
            mulchooses = data.getShow_domain().split(",");
            valuechooses = data.getCar_domain().split(",");
            for (int i = 0; i < mulchooses.length; i++) {
                if (!TextUtils.isEmpty(mulchooses[i])) {
                    datas.add(new FindCarBean(mulchooses[i], valuechooses[i], "domain"));
                }
            }
            // datas.add(new FindCarBean(mFindCarData.getShow_car_type(), "car_type"));
        }

        int size = datas.size();
        for (int i = 0; i < size; i++) {
            View view = layoutInflater.inflate(R.layout.find_view_item, null);
            TextView textView = (TextView) view.findViewById(R.id.text);
            LinearLayout imageView = (LinearLayout) view.findViewById(R.id.close);

            final FindCarBean findCarBean = datas.get(i);
            if (!TextUtils.isEmpty(model)) {
                if ("volume".equals(findCarBean.getType())
                        || "vehicle_model".equals(findCarBean.getType())
                        || "speedchange".equals(findCarBean.getType())
                        || "car_type".equals(findCarBean.getType())) {
//                    imageView.setVisibility(View.GONE);
//                    int padding = DhUtil.dip2px(getActivity(), 6);
//                    view.setPadding(padding * 2, padding, padding * 2, padding);
                    view.setVisibility(View.GONE);
                }
            }
            textView.setText(findCarBean.getTitle());
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if ("brand".equals(findCarBean.getType())) {
                        data.cleanBrand();
                        mSortLinearLayout.setMaxPrice("999");
                    } else if ("model".equals(findCarBean.getType())) {
                        data.setIsCounty(false);
                        data.setCity(MainActivity.main.currentCity);
                        data.cleanBrand();
                        data.setIsCanClick(true);
                        data.setCar_volume("");
                        data.setControl("");
                        data.setVehicle_model("");
                        data.setCar_type("");
                        data.setShow_displacement("");
                        data.setShow_speedchange("");
                        data.setShow_vehicle_model("");
                        data.setShow_car_type("");
                        mSortLinearLayout.setMaxPrice("999");
                    } else if ("age".equals(findCarBean.getType())) {
                        data.setShow_age(replace(findCarBean.getTitle(), data.getShow_age()));
                        data.setYear(replace(findCarBean.getValue(), data.getYear()));
                    } else if ("price".equals(findCarBean.getType())) {
                        data.setPrice("");
                        data.setShow_price("");
                        mSortLinearLayout.clearPrice();
                    } else if ("vehicle_model".equals(findCarBean.getType())) {
                        data.setShow_vehicle_model(replace(findCarBean.getTitle(), data.getShow_vehicle_model()));
                        data.setVehicle_model(replace(findCarBean.getValue(), data.getVehicle_model()));
                    } else if ("car_type".equals(findCarBean.getType())) {
                        data.setShow_car_type(replace(findCarBean.getTitle(), data.getShow_car_type()));
                        data.setCar_type(replace(findCarBean.getValue(), data.getCar_type()));
                    } else if ("color".equals(findCarBean.getType())) {
                        data.setShow_color(replace(findCarBean.getTitle(), data.getShow_color()));
                        data.setColor(replace(findCarBean.getValue(), data.getColor()));
                    } else if ("attribute".equals(findCarBean.getType())) {
                        data.setShow_source(replace(findCarBean.getTitle(), data.getShow_source()));
                        data.setCar_attribute(replace(findCarBean.getValue(), data.getCar_attribute()));
                    } else if ("volume".equals(findCarBean.getType())) {
                        data.setShow_displacement(replace(findCarBean.getTitle(), data.getShow_displacement()));
                        data.setCar_volume(replace(findCarBean.getValue(), data.getCar_volume()));
                    } else if ("speedchange".equals(findCarBean.getType())) {
                        data.setShow_speedchange(replace(findCarBean.getTitle(), data.getShow_speedchange()));
                        data.setControl(replace(findCarBean.getValue(), data.getControl()));
                    } else if ("is_certify".equals(findCarBean.getType())) {
                        data.setIs_certify("0");
                        mSortLinearLayout.setNoGoodCar();
                    } else if ("isCut".equals(findCarBean.getType())) {
                        data.setIsCut("0");
                        mSortLinearLayout.setNoCUT();
                    } else if ("domain".equals(findCarBean.getType())) {
                        data.setShow_domain(replace(findCarBean.getTitle(), data.getShow_domain()));
                        data.setCar_domain(replace(findCarBean.getValue(), data.getCar_domain()));
                    } else if ("mile".equals(findCarBean.getType())) {
                        data.setShowmile(replace(findCarBean.getTitle(), data.getShowmile()));
                        data.setMile(replace(findCarBean.getValue(), data.getMile()));
                    }
                    getData();
                    addFilterView();
                    pullToRefreshListView.setRefreshing();
                    //   initData();

                }
            });
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.setMargins(width, height, 0, height);
            mainLinearLayout.addView(view, lp);
        }

        if (mainLinearLayout.getChildCount() == 0) {
            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, top1, 0, 0);
            mainRelativeLayout.setLayoutParams(lp);
        } else {
            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, top2, 0, 0);
            mainRelativeLayout.setLayoutParams(lp);
        }
    }


    private String replace(String replace, String str) {
        if (str.contains(replace + ",")) {
            return str.replace(replace + ",", "");
        } else {
            return str.replace(replace, "");
        }
    }

    @Override
    public void getCarList(String sort, String price, String brand, String brandName, String model, String modelName, String cut_price, String is_certify) {
        front_cover = 0;
        this.sort = sort;
        this.price = price;
        this.brand = brand;
        this.brand_name = brandName;
        this.model = model;
        this.model_name = modelName;
        this.data.setPrice(price);
        this.data.setShow_price(price + "万");
        this.data.setBrandName(brandName);
        this.data.setBrandSlug(brand);
        this.data.setModelName(modelName);
        this.data.setModelSlug(model);
        this.data.setSort(sort);
        this.isCut = cut_price;
        this.data.setIsCut(cut_price);
        this.is_certify = is_certify;
        this.data.setIs_certify(is_certify);

        addFilterView();
        pullToRefreshListView.setRefreshing();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_BRAND_SORT) {
                Bundle bundle = data.getExtras();
                brand = bundle.getString("brandSlug", "");
                brand_name = bundle.getString("brandName", "");
                model = bundle.getString("modelSlug", "");
                model_name = bundle.getString("modelName", "");


                this.data.setBrandName(brand_name);
                this.data.setBrandSlug(brand);
                this.data.setModelName(model_name);
                this.data.setModelSlug(model);


                mSortLinearLayout.setBrand(brand);
                mSortLinearLayout.setBrandName(brand_name);
                mSortLinearLayout.setModel(model);
                mSortLinearLayout.setModelName(model_name);
                mSortLinearLayout.setBrandColor();
                //front_cover = 1无论接口参数如何返回的都是首屏推荐值
                front_cover = 0;

                if (TextUtils.isEmpty(model) && !TextUtils.isEmpty(brand)) {
                    this.data.setIsCounty(false);
                    this.data.setCity(MainActivity.main.currentCity);
                    cityName = this.data.getCity();
                    this.data.setShow_vehicle_model("");
                    this.data.setShow_car_type("");
                    this.data.setShow_displacement("");
                    this.data.setShow_speedchange("");
                    max_Price = getMaxPriceFromBrand(brand);
                    mSortLinearLayout.setMaxPrice(max_Price);
                    this.data.setCar_type("");
                    this.data.setControl("");
                    this.data.setVehicle_model("");
                    this.data.setCar_volume("");
                    vehicle_model = "";
                    car_volume = "";
                    control = "";
                    car_type = "";
                    addFilterView();
                    pullToRefreshListView.setRefreshing();
                } else {
                    getModelDetailData(brand, model);
                }

            }
        }
    }


    private void getModelDetailData(String brand, String model) {
        if (modelDetailnetWork == null) {
            modelDetailnetWork = new NetDataJson(new NetDataJson.OnStringListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    data.setIsCanClick(true);
                }

                @Override
                public void onDataJsonUpdate(String json) {
                    try {
                        Gson gson = new Gson();
                        ModelDetialBean modelDetialBean = gson.fromJson(json, ModelDetialBean.class);
                        if ("success".equals(modelDetialBean.getStatus())) {
                            getFilterDataFromNet(modelDetialBean);
                        }
                    } catch (Exception e) {
                        data.setIsCanClick(true);
                    }
                }
            }, 1);
        }
        modelDetailnetWork.setUrl(API.modelDetail);
        modelDetailnetWork.addParam("brand", brand);
        modelDetailnetWork.addParam("model", model);
        modelDetailnetWork.request("get");
    }


    private void getFilterDataFromNet(ModelDetialBean modelDetialBean) {
        //车型
        TreeSet<String> vehicleModelSet = new TreeSet<>();
        //产地
        TreeSet<String> carTypeSet = new TreeSet<>();
        //变速箱
        TreeSet<String> controlSet = new TreeSet<>();
        //排量
        TreeSet<String> volumeSet = new TreeSet<>();

        double maxprice = 0;
        for (ModelDetialBean.DetailModelEntity detailModelEntities : modelDetialBean.getDetail_model()) {
            double max = Double.parseDouble(detailModelEntities.getPrice_bn());
            if (max >= maxprice) {
                maxprice = max;
            }
            vehicleModelSet.add(detailModelEntities.getVehicle_model());
            carTypeSet.add(detailModelEntities.getCar_type());
            controlSet.add(detailModelEntities.getControl());
            volumeSet.add(detailModelEntities.getVolume());
        }
        max_Price = (int) maxprice + "";
        mSortLinearLayout.setMaxPrice(max_Price);
        volumeSet.comparator();
        data.clearModelData();
        vehicle_model = "";
        car_volume = "";
        control = "";
        car_type = "";
        String showmoder_name = "";
        String show_speedchangename = "";
        String showcarProperty_name = "";
        String show_displacementname = "";

        int size;
        size = need_carModel.length;
        //遍历车型
        for (String str : vehicleModelSet) {
            for (int i = 0; i < size; i++) {
                if (str.equals(need_carModel[i])) {
                    showmoder_name = showmoder_name + show_carModel[i] + ",";
                }
            }
            vehicle_model = vehicle_model + str + ",";
        }
        if (!TextUtils.isEmpty(vehicle_model)) {
            vehicle_model = vehicle_model.substring(0, vehicle_model.length() - 1);
        }
        if (!TextUtils.isEmpty(showmoder_name)) {
            showmoder_name = showmoder_name.substring(0, showmoder_name.length() - 1);
        }

        size = need_carProperty.length;
        //遍历产地
        for (String str : carTypeSet) {
            for (int i = 0; i < size; i++) {
                if (str.equals(need_carProperty[i])) {
                    showcarProperty_name = showcarProperty_name + show_carProperty[i] + ",";
                }
            }
            car_type = car_type + str + ",";
        }
        if (!TextUtils.isEmpty(car_type)) {
            car_type = car_type.substring(0, car_type.length() - 1);
        }
        if (!TextUtils.isEmpty(showcarProperty_name)) {
            showcarProperty_name = showcarProperty_name.substring(0, showcarProperty_name.length() - 1);
        }


        size = need_speedChange.length;
        //遍历变速箱
        for (String str : controlSet) {
            for (int i = 0; i < size; i++) {
                if (str.equals(need_speedChange[i])) {
                    show_speedchangename = show_speedchangename + show_speedChange[i] + ",";
                }
            }
            control = control + str + ",";
        }
        if (!TextUtils.isEmpty(control)) {
            control = control.substring(0, control.length() - 1);
        }
        if (!TextUtils.isEmpty(show_speedchangename)) {
            show_speedchangename = show_speedchangename.substring(0, show_speedchangename.length() - 1);
        }
        //遍历排量
        for (String str : volumeSet) {
            float volume = Float.parseFloat(str);
            if (volume <= 1.0f) {
                if (car_volume.contains("0-1.0")) continue;
                car_volume = car_volume + "0-1.0" + ",";
                show_displacementname = show_displacementname + "1.0升以内" + ",";
            } else if (volume <= 1.6f && volume >= 1.1f) {
                if (car_volume.contains("1.1-1.6")) continue;
                car_volume = car_volume + "1.1-1.6" + ",";
                show_displacementname = show_displacementname + "1.1-1.6升" + ",";
            } else if (volume <= 2.0f && volume >= 1.7f) {
                if (car_volume.contains("1.7-2.0")) continue;
                car_volume = car_volume + "1.7-2.0" + ",";
                show_displacementname = show_displacementname + "1.7-2.0升" + ",";
            } else if (volume <= 2.5f && volume >= 2.1f) {
                if (car_volume.contains("2.1-2.5")) continue;
                car_volume = car_volume + "2.1-2.5" + ",";
                show_displacementname = show_displacementname + "2.1-2.5升" + ",";
            } else if (volume <= 10.0f && volume >= 2.6f) {
                if (car_volume.contains("2.6-10.0")) continue;
                car_volume = car_volume + "2.6-10.0" + ",";
                show_displacementname = show_displacementname + "2.5升以上" + ",";
            }
        }
        if (!TextUtils.isEmpty(car_volume)) {
            car_volume = car_volume.substring(0, car_volume.length() - 1);
        }
        if (!TextUtils.isEmpty(show_displacementname)) {
            show_displacementname = show_displacementname.substring(0, show_displacementname.length() - 1);
        }
        data.setIsCanClick(false);
        data.setCar_volume(car_volume);
        data.setControl(control);
        data.setVehicle_model(vehicle_model);
        data.setCar_type(car_type);
        data.setShow_displacement(show_displacementname);
        data.setShow_speedchange(show_speedchangename);
        data.setShow_vehicle_model(showmoder_name);
        data.setShow_car_type(showcarProperty_name);
        addFilterView();
        pullToRefreshListView.setRefreshing();
    }


    //判断是否多个城市
    private boolean isMoreCity() {
        if (!TextUtils.isEmpty(provice)) {
            return true;
        }
        String citys[] = cityName.split(",");
        if (citys.length <= 1) {
            return false;
        } else {
            return true;
        }
    }


    public void updateBanner(boolean hasNewCar) {
        if (hasNewCar) {
            banner_ll.setVisibility(View.VISIBLE);
            vip_wayImageView.setVisibility(View.GONE);
        } else {
            banner_ll.setVisibility(View.GONE);
            vip_wayImageView.setVisibility(View.VISIBLE);
        }
    }
}
